var express = require('express');
var path = require('path');
var ejs = require('ejs');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var multer = require('multer');
var errorHandler = require('errorhandler');
var https = require('https');
var _ = require("underscore");
var app = express();
var params = require('express-params');
var nodeschedule = require("./control/node-schedule");
global.app = app;
app.engine('.html', ejs.__express);

app.set('views', __dirname + '/views');
app.set('view engine', 'html');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
console.log("__dirname is:",path.join(__dirname, 'public'));

app.use(express.static(path.join(__dirname, 'public')));

//设置跨域访问
app.post('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Headers", "Content-Type");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


app.use(session({
    secret: "1234567",
    cookie: {maxAge: 24 * 60 * 60 * 1000}, //session 时长为24小时,
    resave: true, // don't save session if unmodified
    saveUninitialized: true // don't create session until something stored
}));


app.use(function (req, res, next) {
    if (req.session && req.session) {
        res.locals = req.session;
    }
    next();
});

nodeschedule.initOrder(function () {
    
});


app.param(['master'], function (req, res, next, master,directory) {
    // 权限控制
    console.log("00000");
    console.log("获取post参数  master",master);
    console.log("directory",directory);
    console.log("111");

    next();
});

var router = require("./router/router.js");
//app.use(router);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    res.end('404 Not Found');
});


// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        console.error("err is:", err);
        res.status(err.status || 500);
        res.end(JSON.stringify({code:500,info:"错误"}));
    });
}

module.exports = app;
